package logic

import (
	"context"
	"yim_server/common/list_query"
	"yim_server/common/models"
	"yim_server/yim_user/user_models"

	"yim_server/yim_user/user_api/internal/svc"
	"yim_server/yim_user/user_api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FriendListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFriendListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FriendListLogic {
	return &FriendListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FriendListLogic) FriendList(req *types.FriendListRequest) (resp *types.FriendListResponse, err error) {

	// 默认值
	defaultPage := 1
	defaultLimit := 10

	// 获取分页参数
	page := defaultPage
	limit := defaultLimit
	if req.Page > 0 {
		page = req.Page
	}
	if req.Limit > 0 {
		limit = req.Limit
	}

	// 最大限制
	maxLimit := 100
	if limit > maxLimit {
		limit = maxLimit
	}

	friendList, count, err := list_query.ListQuery(l.svcCtx.DB, user_models.UserFriendModel{}, list_query.Option{
		PageInfo: models.PageInfo{
			Page:  page,
			Limit: limit,
		},
		Preload: []string{"SendUserModel", "RevUserModel"},
	})
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	var list []types.FriendInfoResponse
	for _, v := range friendList {
		info := types.FriendInfoResponse{}
		// 发起方
		if v.SendUserID == req.UserID {
			info = types.FriendInfoResponse{
				UserID:   v.RevUserID,
				Nickname: v.RevUserModel.Nickname,
				Username: v.RevUserModel.Username,
				Abstract: v.RevUserModel.Abstract,
				Avatar:   v.RevUserModel.Avatar,
				Notice:   v.RevUserNotice,
			}
		}
		if v.RevUserID == req.UserID {
			info = types.FriendInfoResponse{
				UserID:   v.SendUserID,
				Nickname: v.SendUserModel.Nickname,
				Username: v.SendUserModel.Username,
				Abstract: v.SendUserModel.Abstract,
				Avatar:   v.SendUserModel.Avatar,
				Notice:   v.SendUserNotice,
			}
		}
		list = append(list, info)
	}

	return &types.FriendListResponse{
		List:  list,
		Count: int(count),
	}, nil
}
